<template>
  <el-dialog
    v-if="visible"
    v-model="visible"
    :title="$t('components.modifyUseAddress')"
    top="200px"
    :close-on-click-modal="false"
    :append-to-body="visible"
    width="850px"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      :label-width="$t('language') === 'English'? '130px' : '80px'"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-alert
        :title="$t('components.consultWithUsers')"
        type="warning"
        show-icon
      />
      <br>
      <el-form-item
        :label="$t('publics.addressee')"
        prop="receiver"
      >
        <el-input
          v-model="dataForm.receiver"
          maxlength="15"
          :placeholder="$t('shop.consigneeName')"
        />
      </el-form-item>

      <el-form-item
        :label="$t('publics.mobilePhone')"
        prop="mobile"
      >
        <el-input
          v-model="dataForm.mobile"
          :placeholder="$t('publics.mobilePhone')"
          maxlength="11"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('address.province')"
        prop="province"
      >
        <div class="select">
          <el-form-item prop="province">
            <el-select
              v-model="dataForm.provinceId"
              :disabled="order.dvyType === 4"
              :placeholder="$t('tip.select')"
              @change="selectProvince"
            >
              <el-option
                v-for="province in provinceList"
                :key="province.areaId"
                :label="province.areaName"
                :value="province.areaId"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="select">
          <el-form-item prop="city">
            <el-select
              v-model="dataForm.cityId"
              :disabled="order.dvyType === 4"
              :placeholder="$t('tip.select')"
              @change="selectCity"
            >
              <el-option
                v-for="city in cityList"
                :key="city.areaId"
                :label="city.areaName"
                :value="city.areaId"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="select">
          <el-form-item prop="area">
            <el-select
              v-model="dataForm.areaId"
              :placeholder="$t('tip.select')"
              :disabled="!dataForm.cityId || order.dvyType === 4"
              @change="isShowMap ? mapLocation(true) : ''"
            >
              <el-option
                v-for="area in areaList"
                :key="area.areaId"
                :label="area.areaName"
                :value="area.areaId"
              />
            </el-select>
          </el-form-item>
        </div>
      </el-form-item>
      <el-form-item
        :label="$t('address.detailed')"
        prop="addr"
      >
        <el-input
          v-model="dataForm.addr"
          maxlength="30"
          :disabled="order.dvyType === 4"
          :placeholder="$t('address.detailed')"
        />
      </el-form-item>
      <el-form-item v-if="isShowMap">
        <div class="map">
          <tmap
            ref="tmapRef"
            :lat-lng="latLng"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="getChangeAmount()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { isMobile, validNoEmptySpace } from '@/utils/validate'
const emit = defineEmits(['refreshUserAddrOrder'])
const validateMobile = (rule, value, callback) => {
  if (dataForm.value.mobile) {
    const mobile = /^(?:(?:\+|00)86)?1\d{2}([\d*]{4})\d{4}$/
    if (mobile.test(value)) {
      callback()
    } else {
      callback(new Error($t('shopProcess.telErrorTips')))
    }
  } else if (!isMobile(value)) {
    callback(new Error($t('sys.mobilePhoneError')))
  } else {
    callback()
  }
}
const validateAddr = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('shop.addressCannotBeEmpty')))
  } else {
    callback()
  }
}
const validateReceiver = (rule, value, callback) => {
  if (validNoEmptySpace(value)) {
    callback(new Error($t('shopProcess.inputAllSpace')))
  } else {
    callback()
  }
}
const dataRule = reactive({
  receiver: [
    { required: true, message: $t('shop.coneeNameCanEmpty'), trigger: 'blur' },
    { validator: validateReceiver, trigger: 'blur' }
  ],
  addr: [
    { required: true, message: $t('shop.addressCannotBeEmpty'), trigger: 'blur' },
    { validator: validateAddr, trigger: 'blur' }
  ],
  city: [
    { required: true, message: $t('shop.cityCannotBeEmpty'), trigger: 'blur' }
  ],
  province: [
    { required: true, message: $t('shop.provinceCannotBeEmpty'), trigger: 'blur' }
  ],
  area: [
    { required: true, message: $t('shop.districtCounEmpty'), trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: $t('sys.mobilePhoneNoNull'), trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ]
})

const cityList = ref([])
const areaList = ref([])
const order = ref(null)
const provinceList = ref([])
const visible = ref(false)
const dataListLoading = ref(false)
const isShowMap = ref(false)
const oldOrder = ref('')
const freightAmount = ref(0)
const orderStatus = ref(0)
const latLng = ref(null)
const dataForm = ref({
  addrOrderId: 0,
  addrId: 0,
  addr: '',
  receiver: '',
  mobile: '',
  area: '',
  city: '',
  province: '',
  areaId: null,
  cityId: null,
  provinceId: null
})
// 获取数据列表
const init = (orderParam) => {
  const orderInfo = Object.assign({}, orderParam)
  const userAddr = orderInfo.userAddrOrder
  order.value = orderInfo
  visible.value = true
  dataListLoading.value = true
  dataForm.value = userAddr
  isShowMap.value = Boolean((orderInfo.dvyType === 4 && (orderInfo.status === 1 || orderInfo.status === 2)))
  freightAmount.value = orderInfo.freightAmount
  orderStatus.value = orderInfo.status
  oldOrder.value = JSON.parse(JSON.stringify(orderInfo))
  listAreaByParentId().then(({ data }) => {
    provinceList.value = data
  })
  if (userAddr.provinceId && userAddr.cityId) {
    listAreaByParentId(userAddr.provinceId).then(({ data }) => {
      cityList.value = data
    })
    listAreaByParentId(userAddr.cityId).then(({ data }) => {
      areaList.value = data
    })
  }
  dataListLoading.value = false
}
defineExpose({ init })

const getCurrentChild = (curList, curId) => {
  for (const item of curList) {
    if (item.areaId === curId) {
      return {
        curNode: item,
        areas: item.areas
      }
    }
  }
}
const listAreaByParentId = (pid) => {
  let paramData = {}
  if (!pid) {
    paramData = { level: 1 }
  } else {
    paramData = { pid }
  }
  return http({
    url: http.adornUrl('/admin/area/listByPid'),
    method: 'get',
    params: http.adornParams(paramData)
  })
}
// 选择省
const selectProvince = (val) => {
  dataForm.value.cityId = null
  dataForm.value.city = ''
  dataForm.value.areaId = null
  dataForm.value.area = ''
  // 获取城市的select
  const { curNode, areas } = getCurrentChild(provinceList.value, val)
  if (areas) {
    cityList.value = areas
  } else {
    listAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      cityList.value = data
    })
  }
  if (!isShowMap.value) {
    return false
  }
}
// 选择市
const selectCity = (val) => {
  dataForm.value.areaId = null
  dataForm.value.area = ''
  // 获取区的select
  const { curNode, areas } = getCurrentChild(cityList.value, val)
  if (areas) {
    areaList.value = areas
  } else {
    listAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      areaList.value = data
    })
  }
  if (!isShowMap.value) {
    return false
  }
}
const getAddr = () => {
  for (let i = 0; i < provinceList.value.length; i++) {
    if (provinceList.value[i].areaId === dataForm.value.provinceId) {
      // 将省名字保存起来
      dataForm.value.province = provinceList.value[i].areaName
    }
  }
  for (let i = 0; i < cityList.value.length; i++) {
    if (cityList.value[i].areaId === dataForm.value.cityId) {
      // 将市名字保存起来
      dataForm.value.city = cityList.value[i].areaName
    }
  }
  for (let i = 0; i < areaList.value.length; i++) {
    if (areaList.value[i].areaId === dataForm.value.areaId) {
      // 将市名字保存起来
      dataForm.value.area = areaList.value[i].areaName
    }
  }
}

const dataFormRef = ref(null)
const getChangeAmount = () => {
  oldOrder.value.orderId = order.value.orderId
  oldOrder.value.orderNumber = order.value.orderNumber
  getAddr()
  dataFormRef.value?.validate(valid => {
    if (valid) {
      // 同城配送仅支持修改收件人信息不需要请求运费接口
      if (order.value.dvyType === 4) {
        submitProds()
        return
      }
      http({
        url: http.adornUrl('/order/order/getChangeAmount'),
        method: 'get',
        params: http.adornParams({
          orderId: oldOrder.value.orderId,
          orderNumber: oldOrder.value.orderNumber,
          areaId: order.value.userAddrOrder.areaId,
          lng: dataForm.value.lng ? dataForm.value.lng : '',
          lat: dataForm.value.lat ? dataForm.value.lat : ''
        })
      }).then(({ data }) => {
        const msg = `${$t('shop.changeAmountTip1')}${data > 0 ? $t('shop.overcharged') : $t('shop.undercharged')}${$t('shop.by')}${data < 0 ? data * -1 : data}${$t('shop.yuan')}${$t('shop.changeAmountTip2')}`
        ElMessageBox.confirm(msg, $t('text.tips'), {
          confirmButtonText: $t('order.confirm'),
          cancelButtonText: $t('order.cancel'),
          type: 'warning'
        }).then(() => {
          submitProds()
        })
      })
    }
  })
}
// 确定事件
const submitProds = () => {
  getAddr()
  dataFormRef.value?.validate(valid => {
    if (valid) {
      http({
        url: http.adornUrl('/order/order/changeUserAddr'),
        method: 'put',
        data: http.adornData({
          orderId: order.value.orderId,
          orderNumber: order.value.orderNumber,
          userAddrOrder: dataForm.value
        })
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshUserAddrOrder')
          }
        })
      })
    }
  })
}
</script>

<style scoped>
div :deep(.el-form-item){
  margin-top: 20px !important;
}
.select {
  width: 220px;
  display: inline-block;
  margin-top:-20px;
}
.map {
  width: 100%;
  height: 500px;
}
</style>
